package 树;
/**
 * https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
 */
public class _106_从中序与后序遍历序列构造二叉树 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder,0, inorder.length-1,
                     postorder,0, postorder.length-1);
    }

    /*
       若中序遍历数组为 inorder[inStart..inEnd]，
       后序遍历数组为 postorder[postStart..postEnd]，
       构造二叉树，返回该二叉树的根节点
    */
    private TreeNode build(int[] inorder, int inStart, int inEnd,
                                                int[] postorder, int postStart, int postEnd){
        if(inStart > inEnd) return null;
        int rooVal = postorder[postEnd]; //后序遍历中根节点的值为最后一个元素
        int index = -1;//记录中序遍历中，根节点所在的索引1
        for(int i=inStart;i<=inEnd;++i){
            if(rooVal == inorder[i]){
                index = i;
                break;
            }
        }
        //可以在中序遍历中计算出左子树的个数，
        int leftSize = index - inStart;

        //构造根节点
        TreeNode root = new TreeNode(rooVal);
        //递归的在左子树和右子树构造根节点，控制好数组的索引
        root.left = build(inorder,inStart,index-1,
                postorder,postStart,postStart+leftSize-1);
        root.right = build(inorder,index+1,inEnd,
                postorder,postStart+leftSize,postEnd-1);

        return root;
    }

    private TreeNode build2(int[] inorder, int inStart, int inEnd,
                           int[] postorder, int postStart, int postEnd){
        if(inStart > inEnd){
            return null;
        }
        int rootVal = postorder[postEnd];
        int index = -1;
        for (int i = inStart; i <= inEnd; i++) {
            if(rootVal == inorder[i]){
                index = i;
                break;
            }
        }

        int leftSize = index - inStart;
        TreeNode root = new TreeNode(rootVal);

        root.left = build(inorder,inStart,index -1,
                          postorder,postStart,postStart+leftSize-1);

        root.right = build(inorder,index+1,inEnd,
                           postorder,postStart+leftSize,postEnd-1);

        return root;
    }
}
